#encoding: utf-8

import sys
from urllib import request
from urllib import parse
from http.cookiejar import CookieJar

import json
from xlutils.copy import copy
import xlwt, xlrd

import pymysql

def start(dayStart, dayEnd):
    #dayStart = '2018-06-24'
    #dayEnd = '2019-04-11'
    headers = {#'Cookie':'UniqueID=4pJSPKnp6s7XqvEK1554949714583; Sites=_21; _ga=GA1.3.491390293.1554949714; _gid=GA1.3.1102093920.1554949714; 21_vq=7',
            'Referer':'http://www.cwl.gov.cn/kjxx/ssq/kjgg/',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
    url = 'http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart='+dayStart+'&dayEnd='+dayEnd+'&pageNo='
    print(url)
    req = request.Request(url = url, headers = headers)
    resp = request.urlopen(req)
    res_data = resp.read().decode('utf-8')
    json_data = json.loads(res_data)
    result = json_data['result']
    #append_excel('./dlottery.xls', json_data['result'])
    #save_db(json_data['result'])
    save_file(result)
    #print(result)

def save_file(contents):
    with open('./lottery.txt', 'w', encoding='utf-8') as fp:
        fp.write(str(contents))
    fp.close()

    f = open('./dlottery.txt', 'a+')
    for obj in contents:
        code = obj['code']
        date = obj['date']
        blue = obj['blue']
        red = obj['red']
        f.write(code)
        f.write(',')
        f.write(date)
        f.write(',')
        f.write(blue)
        f.write(',')
        f.write(red)
        f.write('\n')
    f.close()

def save_db(contents):
    db_config = {
        'host':'192.168.184.2',
        'port':3306,
        'user':'root',
        'passwd':'rootroot',
        'db':'boot_plus',
        'charset':'utf8'
    }
    conn = pymysql.connect(**db_config)
    cursor = conn.cursor()
    str_sql = 'select * from lottery'
    cursor.execute(str_sql)
    result = cursor.fetchall()
    print(result)
    

def append_excel(path, contents):
    workbook = xlrd.open_workbook(path)
    sheets = workbook.sheet_names()
    worksheet = workbook.sheet_by_name(sheets[0])
    rows_old = worksheet.nrows
    new_workbook = copy(workbook)
    new_worksheet = new_workbook.get_sheet(0)
    try:
        index = rows_old + 1
        for obj in contents:
            code = obj['code']
            new_worksheet.write(index, 0, code)
            date = obj['date']
            new_worksheet.write(index, 1, date)
            blue = obj['blue']
            bidx = int(blue)
            bidx += 34            
            new_worksheet.write(index, bidx, blue)
            reds = obj['red']
            rlist = reds.split(',')
            for red in rlist:
                ridx = int(red)
                ridx += 1
                new_worksheet.write(index, ridx, red)
            index += 1
    except:
        print(sys.exec_info()[0])
        pass
    new_workbook.save(path)


if __name__ == '__main__':
    print('__main__')
    args = sys.argv
    print(args)
    start(args[1], args[2])
    
